import Taro from "@tarojs/taro";
import { DocumentNode } from "graphql";
import { useCallback, useEffect, useState } from "react"
import getToken from "./getToken";
export type UseQueryOption = {
    variables?: any,
    autoFetch?: boolean
}
const useQuery = <T = any>(query: DocumentNode, { variables, autoFetch }: UseQueryOption = { autoFetch: true }) => {
    const [data, setData] = useState<T>();
    const [error, setError] = useState();
    const [loading, setLoading] = useState(true);
    const refetch = useCallback(async (variables?: any) => {
        setLoading(true)
        const token = await getToken()
        Taro.request({
            method: "POST",
            url: "http://localhost:14530/graphql",
            header: {
                'Authorization': `Bearer ${token}`
            },
            data: {
                query: query.loc?.source.body,
                variables
            }
        }).then(({ data: { data, errors } }) => {
            setData(data)
            setError(errors)
        }).catch(e => {
            setError(e);
        }).finally(() => {
            setLoading(false);
        })
    }, [])
    useEffect(() => {
        if (autoFetch) refetch(variables)
    }, []);
    return { data, error, loading, refetch }
}
export default useQuery